package com.gis3c.online.service.impl;

import com.gis3c.common.exception.BusinessException;
import com.gis3c.online.common.BussinessUtils;
import com.gis3c.online.dao.AirDao;
import com.gis3c.online.entry.AirStation;
import com.gis3c.online.service.AirService;
import com.gis3c.spatial.common.FeatureUtilities;
import com.gis3c.spatial.common.GeometryUtilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by hukekuan on 2018/3/16.
 */
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class AirServiceImpl implements AirService {
    @Autowired
    private AirDao airDao;

    @Override
    public String findAirStationListByParans(Map<String,Object> params) {
        String result = null;
        List<AirStation> stationList = airDao.findAirStationListByParans();
        List<AirStation> resultList = null;
        if(params.keySet().size() == 0){
            resultList = stationList;
        }else {
            resultList = new ArrayList<>();
            for(AirStation airStation:stationList){
                if(params.containsKey("stcode")
                        && !params.get("stcode").equals(airStation.getStCode())){
                    continue;
                }
                if(params.containsKey("stationName")
                        && airStation.getStationName().indexOf(params.get("stationName").toString()) < 0){
                    continue;
                }
                if(params.containsKey("aqiLevel")
                        && !params.get("aqiLevel").equals(airStation.getLevel())){
                    continue;
                }
                if(params.containsKey("mainPollute")
                        && !params.get("mainPollute").equals(airStation.getItemCode().trim())){
                    continue;
                }
                if(params.containsKey("adminCode")
                        && !BussinessUtils.AdminCodeCheck(airStation.getAdminCode().toString(),(String[])params.get("adminCode"))){
                    continue;
                }

                resultList.add(airStation);
            }
        }

        resultList.forEach(airStation -> airStation.setGeometry(
                GeometryUtilities.CreatePoint(airStation.getLongitude(),airStation.getLatitude())));
        try{
            result = FeatureUtilities.JavaBeans2Json(resultList);
        }catch (IllegalAccessException | IOException e) {
            throw new BusinessException("AirStation实体转GeoJSON出错");
        }
        return result;
    }
}
